package com.xiaoq.sites.endpoint;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.apis.interpreter.Inter4SPUVo;
import com.xiaoq.apis.order.IOrderApi;
import com.xiaoq.apis.order.ISPUApi;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4InterVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;
import com.xiaoq.sites.entity.InterDicEntity;
import com.xiaoq.sites.entity.InterpreterEntity;
import com.xiaoq.sites.service.IInterDicService;
import com.xiaoq.sites.service.IInterpreterService;
import com.xiaoq.sites.vo.Interpreter4Add;
import com.xiaoq.sites.vo.InterpreterVo;
import com.xiaoq.vo.PagingVo;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/inters")
@Api(tags = "B端讲解员部分（CRUD）")
public class InterpreterEndpoint2B {
	
	private static final class InterpreterListResponse extends GenericListResponse<InterpreterVo> {};

	private static final class InterpreterResponse extends GenericDataResponse<Interpreter4Add> {};

	private final Logger LOGGER = LoggerFactory.getLogger(InterpreterEndpoint2B.class);

	@Autowired
	private RedisTemplate4JedisCluster redisTemplate4JedisCluster;
	
	//@Reference(interfaceClass=IInterpreterApi.class, check=false, version="1.0.0")
	@Autowired
	private IInterpreterService interpreterService;

	@Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
	private IUserApi userDubboApi;

	@Reference(interfaceClass=ISPUApi.class, check=false, version="1.0.0")
	private ISPUApi spuApi;

	@Reference(interfaceClass=IOrderApi.class, check=false, version="1.0.0")
	private IOrderApi orderApi;

	@Autowired
	private IdGenerator idGenerator;

	@Autowired
	private IInterDicService interDicService;
	
	@ApiOperation(value="新增讲解员", notes="新增讲解员")
	@ApiResponses({
		@ApiResponse(code = 200, response = GenericResponse.class, message = "新增讲解员")
	})
	@PostMapping(value="", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> add(HttpServletRequest request,
								 @ModelAttribute(value = "interpreter4Add") @ApiParam(value = "interpreter4Add", required = true) Interpreter4Add interpreter4Add,
								 @RequestParam(value = "file", required = false) @ApiParam(value = "图片", required = false)  MultipartFile file) {

		if(interpreter4Add == null){
			return GenericResponse.ng("RequestBody 不能为空");
		}

		String mobile = interpreter4Add.getMobile();
		if (StringUtils.isBlank(mobile)){
			return GenericResponse.ng("电话不能为空");
		}

		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);
		String imgUrl = "";
		try {
			if (file != null && file.getSize()>0) {
				imgUrl = UploadUtil.easyUploadByte(file, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				interpreter4Add.setImgUrl(imgUrl);
			}
		} catch (Exception e) {
			LOGGER.error("七牛云上传异常！", e);
			return GenericResponse.ng("图片上传失败！");
		}

		InterpreterEntity interpreterEntity = new InterpreterEntity();
		long price = interpreter4Add.getPrice()==null?0L:interpreter4Add.getPrice();
		interpreter4Add.setPrice(price * 100);
		BeanUtils.copyProperties(interpreter4Add, interpreterEntity);
		interpreterEntity.setSitesId(shopId);
		String interId = idGenerator.nextId();
		interpreterEntity.setId(interId);
		interpreterEntity.setStatus(ConstantUtil.INTERPRETER_STATUS_WAIT_SERVICE_CAN_APPOINT);
//		if(CollectionUtils.isNotEmpty(interpreter4Add.getNotSvrTimes())){
//			//保存讲解员日历
//			DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
//			for (String dateTimeStr : interpreter4Add.getNotSvrTimes()){
//				DateTime startTime = DateTime.parse(dateTimeStr, format).withTime(8,0,0,0);
//				DateTime endTime = DateTime.parse(dateTimeStr, format).withTime(18,0,0,0);
//				InterpreterCalendarEntity calendarEntity = new InterpreterCalendarEntity();
//				calendarEntity.setId(idGenerator.nextId());
//				calendarEntity.setInterpreterId(interId);
//				calendarEntity.setStartTime(startTime.getMillis());
//				calendarEntity.setEndTime(endTime.getMillis());
//				calendarEntity.setType(20);
//				interpreterService.saveInterCalendar(calendarEntity);
//			}
//		}

		//根据电话查询讲解员是否为小Q的用户
		String userInterpreterId = "";
		try {
			UserInfo4InterVo userInfo4InterVo = userDubboApi.getUserByMobile(mobile);
			if(userInfo4InterVo != null){
				if(userInfo4InterVo.isInterpreter()){
					userInterpreterId = userInfo4InterVo.getId();
				}else{
					//添加讲解员的角色到user
					boolean addFlag = userDubboApi.addInterRole2UserByUserId(userInfo4InterVo.getId());
					if(!addFlag){
						LOGGER.error("添加讲解员角色到用户失败,讲解员ID:{},电话:{}",interId, mobile);
					}
				}
			}
		}catch (Exception e){
			LOGGER.error("新增讲解员失败, 添加讲解员角色到User Dubbo调用失败", e.getMessage());
		}
		interpreterEntity.setUserId(userInterpreterId); //设置讲解员账户关联（APP和讲解员）
		interpreterService.saveInter(interpreterEntity);
		Inter4SPUVo inter4SPUVo = new Inter4SPUVo();
		inter4SPUVo.setImgUrl(interpreter4Add.getImgUrl());
		inter4SPUVo.setName(interpreter4Add.getName());
		inter4SPUVo.setInterpreterId(interId);
		inter4SPUVo.setShopId(shopId);
		inter4SPUVo.setPrice(interpreter4Add.getPrice());

		try {
			spuApi.save(inter4SPUVo);
		}catch (Exception e){
			LOGGER.error("新增讲解员失，调用dubbo服务失败- spuApi.save()", e.getMessage());
		}

		return GenericResponse.ok();
	}

	@ApiOperation(value="获取讲解员列表", notes="获取讲解员列表")
	@ApiResponses({
			@ApiResponse(code = 200, response = InterpreterListResponse.class, message = "获取讲解员列表")
	})
	@GetMapping(value="", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> list(HttpServletRequest request,
								  @ApiParam(value="pn", required=false) @RequestParam(required = false, defaultValue = "1") int pn,
								  @ApiParam(value="ps", required=false) @RequestParam(required = false, defaultValue = "10") int ps) {

		PagingVo pagingVo = new PagingVo(pn, ps);
		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);
		List<InterpreterVo> resultList = new ArrayList<>();
		List<InterpreterEntity> interList = interpreterService.findInterpreterListBySitesId(shopId, null, pagingVo);
		long totalCount = interpreterService.findInterpreterListCountBySitesId(shopId, null);
		if(CollectionUtils.isEmpty(interList)){
			return InterpreterListResponse.listAndCount(resultList, resultList.size());
		}

		List<String> interIdList = interList.stream().map(item->item.getId()).collect(Collectors.toList());

		Map<String, Integer> interId2CountMap = null;
		try {
			interId2CountMap = orderApi.getInterOrderPaidCount(shopId, interIdList);
		}catch (Exception e){
			LOGGER.error(e.getMessage() + "远程调用（预约数量）DUBBO 失败", e);
		}

		if(interId2CountMap == null){
			interId2CountMap = new HashMap<>();
		}

		Map<String, Double> interId2Score = null;
		try {
			interId2Score = spuApi.getReviewScore4InterByShopId(shopId);
		}catch (Exception e){
			LOGGER.error(e.getMessage() + "远程调用(讲解员评分)DUBBO失败", e);
		}
		if(interId2Score == null){
			interId2Score = new HashMap<>();
		}

		InterpreterVo interpreterVo = null;
		for(InterpreterEntity interpreterEntity : interList){
			interpreterVo = new InterpreterVo();
			BeanUtils.copyProperties(interpreterEntity, interpreterVo);
			String tmpInterId = interpreterVo.getId();

			Double score = interId2Score.get(tmpInterId);
			interpreterVo.setAvgStar(score==null?0D:score);

			Integer orderCount = interId2CountMap.get(tmpInterId);
			interpreterVo.setOrderCount(orderCount==null?0:orderCount);

			resultList.add(interpreterVo);
		}

		return InterpreterListResponse.listAndCount(resultList, totalCount);
	}

	@ApiOperation(value="修改讲解员", notes="修改讲解员")
	@ApiResponses({
			@ApiResponse(code = 200, response = GenericResponse.class, message = "修改讲解员")
	})
	@PostMapping(value="/{interId}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> update(HttpServletRequest request,
									@PathVariable("interId") @ApiParam(value="interId", required=true) String interId,
									@ModelAttribute(value = "interpreter4Add")
										@ApiParam(value = "interpreter4Add", required = true) Interpreter4Add interpreter4Add
			,@RequestParam(value = "file", required = false) @ApiParam(value = "图片", required = false) MultipartFile file) {
		if(interpreter4Add == null){
			return GenericResponse.ng("RequestBody 不能为空");
		}

		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);

		InterpreterEntity oldInterEntity = interpreterService.findInterpreterById(interId);

		if(oldInterEntity==null || !StringUtils.equals(oldInterEntity.getSitesId(), shopId)){
			return GenericResponse.ng("此讲解员不存在");
		}
		String oldMobile = oldInterEntity.getMobile();
		String newMobile = interpreter4Add.getMobile();
		String imgUrl = "";
		try {
			if (file != null && file.getSize()>0) {
				imgUrl = UploadUtil.easyUploadByte(file, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				interpreter4Add.setImgUrl(imgUrl);
			}
		} catch (Exception e) {
			LOGGER.error("七牛云上传异常！", e);
			return GenericResponse.ng("图片上传失败！");
		}

		InterpreterEntity interpreterEntity = new InterpreterEntity();

		if(interpreter4Add.getPrice()==null || interpreter4Add.getPrice()<1){
			return GenericResponse.ng("讲解员的价格不能为空或小于1");
		}

		long price = interpreter4Add.getPrice();
		interpreter4Add.setPrice(price * 100);
		BeanUtils.copyProperties(interpreter4Add, interpreterEntity);
		interpreterEntity.setId(interId);
		interpreterEntity.setSitesId(shopId);
		interpreterService.updateInterpreterByIdAndSitesId(interpreterEntity);
		Inter4SPUVo inter4SPUVo = new Inter4SPUVo();
		inter4SPUVo.setImgUrl(interpreter4Add.getImgUrl());
		inter4SPUVo.setName(interpreter4Add.getName());
		inter4SPUVo.setInterpreterId(interId);
		inter4SPUVo.setShopId(shopId);
		inter4SPUVo.setPrice(interpreter4Add.getPrice());

		try {
			spuApi.updateByInterId(inter4SPUVo);
		}catch (Exception e){
			LOGGER.error("调用dubbo服务失败- spuApi.updateByInterId()", e.getMessage());
		}
		String interpreterUserId = "";
		if(StringUtils.isNotBlank(newMobile) && !StringUtils.equals(newMobile, oldMobile)){
			//删除以前关联APP用户的讲解员权限
			userDubboApi.removeUserInterRole(oldInterEntity.getUserId());
			UserInfo4InterVo userInfo4InterVo = userDubboApi.getUserByMobile(newMobile);
			if(userInfo4InterVo != null){
				if(userInfo4InterVo.isInterpreter()){
					interpreterUserId = userInfo4InterVo.getId();
				}else {
					//添加讲解员的角色到user
					boolean addFlag = userDubboApi.addInterRole2UserByUserId(userInfo4InterVo.getId());
					if(!addFlag){
						LOGGER.error("添加讲解员角色到用户失败,讲解员ID:{},电话:{}",interId, newMobile);
					}
				}
			}
		}

		if(StringUtils.isNotBlank(interpreterUserId)){
			//更新讲解员的userId
			InterpreterEntity updateInter = new InterpreterEntity();
			updateInter.setId(interId);
			updateInter.setUserId(interpreterUserId);
			interpreterService.updateByInterId(updateInter);
		}

		return GenericResponse.ok();
	}

	@ApiOperation(value="修改讲解员是否接单", notes="修改讲解员是否接单")
	@ApiResponses({
			@ApiResponse(code = 200, response = GenericResponse.class, message = "修改讲解员是否接单")
	})
	@PutMapping(value="/{interId}/{status}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> update4Orders(HttpServletRequest request,
										   @PathVariable("interId") @ApiParam(name="interId", value="讲解员Id", required=true) String interId,
										   @PathVariable("status") @ApiParam(name="status", value="-1:不接单，0:可接单") int status) {
		InterpreterEntity interpreterEntity = interpreterService.findInterpreterById(interId);
		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);
		if(interpreterEntity==null || !StringUtils.equals(shopId, interpreterEntity.getSitesId())){
			return GenericResponse.ng("此讲解员不存在或（讲解员的景区ID不和当前用户的景区ID一致）");
		}

		if(interpreterEntity.getStatus() == null){
			return GenericResponse.ng("此讲解员状态错误");
		}

		int currentInterStatus = interpreterEntity.getStatus().intValue();
		//将讲解员修改为不可接单
		if(status==ConstantUtil.INTERPRETER_STATUS_WAIT_SERVICE_CAN_APPOINT ||
				status==ConstantUtil.INTERPRETER_STATUS_NOT_SERVICE){
			InterpreterEntity newInterpreter = new InterpreterEntity();
			newInterpreter.setId(interpreterEntity.getId());
			newInterpreter.setSitesId(interpreterEntity.getSitesId());
			newInterpreter.setStatus(status);
			interpreterService.updateInterpreterByIdAndSitesId(newInterpreter);
			return GenericResponse.ok();
		}else {
			return GenericResponse.ng("传入的讲解员的状态status不对");
		}
	}

	@ApiOperation(value="讲解员详情", notes="讲解员详情")
	@ApiResponses({
			@ApiResponse(code = 200, response = InterpreterResponse.class, message = "讲解员详情")
	})
	@GetMapping(value="/{interId}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> get(HttpServletRequest request,
									@PathVariable("interId") @ApiParam(value="interId", required=true) String interId) {

		InterpreterEntity interpreterEntity = interpreterService.findInterpreterById(interId);
		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);
		if(interpreterEntity == null || !StringUtils.equals(shopId, interpreterEntity.getSitesId())){
			return GenericResponse.ng("此讲解员不存在");
		}
		Interpreter4Add interpreter4Add = new Interpreter4Add();
		BeanUtils.copyProperties(interpreterEntity, interpreter4Add);
		interpreter4Add.setPrice(interpreter4Add.getPrice()/100);

		List<InterDicEntity> interDicList = interDicService.getAllInterDicList(ConstantUtil.DIC_TYPE_4_INTER_LANG, null);
		Map<String, String> dicId2ValueMap = new HashMap<>();
		if(CollectionUtils.isNotEmpty(interDicList)){
			for(InterDicEntity interDicEntity : interDicList){
				dicId2ValueMap.put(interDicEntity.getDicId(), interDicEntity.getDicValue());
			}
		}

		List<String> langIds = interpreter4Add.getSvcLang();
		List<String> newLangVals = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(langIds)){
			for(String langId : langIds){
				String dicVal = dicId2ValueMap.get(langId);
				if(StringUtils.isNotBlank(dicVal)){
					newLangVals.add(dicVal);
				}
			}
		}

		interpreter4Add.setSvcLang(newLangVals);
		return InterpreterResponse.okWithData(interpreter4Add);
	}

	@ApiOperation(value="删除讲解员", notes="删除讲解员")
	@ApiResponses({
			@ApiResponse(code = 200, response = GenericResponse.class, message = "删除讲解员")
	})
	@DeleteMapping(value="/{interId}", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> delete(HttpServletRequest request,
								 @PathVariable("interId") @ApiParam(value="interId") String interId) {

		InterpreterEntity interpreterEntity = interpreterService.findInterpreterById(interId);
		String mgrId = (String) request.getAttribute("userId");
		String shopId = redisTemplate4JedisCluster.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, mgrId);
		if(interpreterEntity == null || !StringUtils.equals(shopId, interpreterEntity.getSitesId())){
			return GenericResponse.ng("此讲解员不存在");
		}

		boolean delFlag = interpreterService.deleteByIdAndSitesId(interId, shopId);
		if(delFlag){
			try {
				boolean dubboDelFlag = spuApi.deleteByInterIdAndSitesId(interId, shopId);
				if(!dubboDelFlag){
					LOGGER.error("Dubbo 删除讲解员失败,sitesId: " + shopId + ",interId: " + interId);
				}
			}catch (Exception e){
				LOGGER.error("Dubbo 删除讲解员失败,sitesId: " + shopId + ",interId: " + interId, e.getMessage());
			}

			if(StringUtils.isNotBlank(interpreterEntity.getUserId())){
				try {
					boolean dubboDelFlag = userDubboApi.removeUserInterRole(interId);
					if(!dubboDelFlag){
						LOGGER.error("Dubbo 删除APP端用户讲解员权限失败,sitesId: " + shopId + ",interId: " + interId);
					}
				}catch (Exception e){
					LOGGER.error("Dubbo 删除APP端用户讲解员权限失败,sitesId: " + shopId + ",interId: " + interId, e.getMessage());
				}
			}
			return GenericResponse.ok();
		}

		return GenericResponse.ng("删除interId：" + interId + "的讲解员失败");
	}


}
